using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Templates_ImageCompetition : BaseTemplate
{
    protected void Page_Load(object sender, EventArgs e )
    {
        aveRating.Attributes.Add("onclick", "return false;"); 
        if (!IsPostBack)
        {
            dlEntrants.DataBind();
            HyperLink lnkLogin = viewEnter.FindControl("lnkLogin") as HyperLink;
            if (lnkLogin != null)
            {
                lnkLogin.NavigateUrl = string.Concat("~/Login.aspx?ReturnUrl=", CurrentUrl);
            }
            DataBind();
        }
    }

    public override void DataBind()
    {
        viewEnter.DataBind();
        pnlSelected.DataBind();
        dlEntrants.DataBind();
    }

    protected void btnEnter_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            TextBox txtTitle = viewEnter.FindControl("txtTitle") as TextBox;
            TextBox txtComment = viewEnter.FindControl("txtComment") as TextBox;
            FileUpload fuImage = viewEnter.FindControl("fuImage") as FileUpload;
            Panel pnlFileError = viewEnter.FindControl("pnlFileError") as Panel;
            if (txtTitle != null && txtComment != null && fuImage != null && pnlFileError != null && fuImage.HasFile)
            {
                if (fuImage.PostedFile.ContentLength > 3000000)
                {
                    pnlFileError.Visible = true;
                    return;
                }
                Acms.Bll.UserPostUpload upload = Acms.Bll.UserPostUpload.CreateInstance(User.Identity.User.Id, PostId, System.Net.IPAddress.Parse(Request.UserHostAddress));
                upload.Title = txtTitle.Text;
                upload.Comment = txtComment.Text;

                try
                {
                    upload.Update(Acms.Bll.File.FileTypes.Image, fuImage.PostedFile, fuImage.FileBytes);
                }
                catch(Acms.Exceptions.InvalidFileTypeException)
                {
                    pnlFileError.Visible = true;
                    return;
                }
                
                Acms.Bll.Email email = Acms.Bll.Email.CreateInstance(User.Identity.User, MapPath("~/Emails/PhotoCompetition.xml"));
                email.Format("EntryDate", DateTime.Now.ToLongDateString());
                email.Format("CompetitionName", CurrentPostDisplayName);
                email.Send();

                DataBind();
                updEntrants.Update();
            }
        }
    }

    protected void viewEnter_DataBinding(object sender, EventArgs e)
    {
        Panel pnlNotEntered = viewEnter.FindControl("pnlNotEntered") as Panel;
        Panel pnlEntered = viewEnter.FindControl("pnlEntered") as Panel;
        LinkButton btnViewEntry = viewEnter.FindControl("btnViewEntry") as LinkButton;
        if (pnlEntered != null && pnlNotEntered != null && btnViewEntry != null)
        {
            Acms.Bll.UserPostUpload currentUsers = GetCurrentUsersUpload();
            if (currentUsers != null)
            {
                btnViewEntry.CommandArgument = currentUsers.Id.ToString();
                pnlEntered.Visible = true;
                pnlNotEntered.Visible = false;
            }
            else
            {
                pnlEntered.Visible = false;
                pnlNotEntered.Visible = true;
            }
            
        }
    }

    private Acms.Bll.UserPostUpload GetCurrentUsersUpload()
    {
        if(User != null && User.Identity != null && User.Identity.User != null)
        {
            List<Acms.Bll.UserPostUpload> tmp = Acms.Bll.UserPostUpload.GetAllByUserIdAndPostId(User.Identity.User.Id, PostId);
            if (tmp != null && tmp.Count > 0)
            {
                return tmp[0];
            }
        }
        return null;
    }

    protected void btnDeleteEntry_Click(object sender, EventArgs e)
    {
        Acms.Bll.UserPostUpload tmp = GetCurrentUsersUpload();
        if (tmp != null)
        {
            tmp.Delete();
            DataBind();
            updEntrants.Update();
        }
    }

    protected void dsEntrants_SelectData(object sender, Acms.DataControls.SelectEventArgs<Acms.Bll.UserPostUpload> e)
    {
        e.SetData(Acms.Bll.UserPostUpload.GetAllByPostId(PostId));
    }

    private int selectedId;
    private Acms.Bll.UserPostUploadAverage selected;
    protected Acms.Bll.UserPostUploadAverage Selected
    {
        get
        {
            if (selected == null && selectedId > 0)
                selected = Acms.Bll.UserPostUploadAverage.GetById(selectedId);
            return selected;
        }
        set
        {
            selected = value;
            if (selected != null)
                selectedId = selected.Id;
            else
                selectedId = 0;
        }
    }

    protected override object SaveViewState()
    {
        ViewState["SelctedId"] = selectedId;
        ViewState["HasRatedSelect"] = hasRatedSelect;
        return base.SaveViewState();
    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        if(ViewState["SelctedId"] is int)
            selectedId = (int)ViewState["SelctedId"];
        if (ViewState["HasRatedSelect"] is bool)
            hasRatedSelect = (bool)ViewState["HasRatedSelect"];
    }

    bool hasRatedSelect;

    protected void pnlSelected_DataBinding(object sender, EventArgs e)
    {
        if (Selected == null)
        {
            pnlSuspended.Visible = false;
            pnlSelected.Visible = false;
        }
        else
        {
            pnlSuspended.Visible = false;
            pnlSelected.Visible = true;
            lblUserName.Text = Selected.UserName;
            lblCreatedTime.Text = Selected.Created.ToString();
            imgSelected.FileId = Selected.FileId;
            lblTitle.Text = Selected.Title;
            if (Selected.Comment != null)
            {
                litComment.Text = Selected.Comment.Replace("\n", "<br/>");
            }
            else
            {
                litComment.Text = "";
            }
            //your rating
            hasRatedSelect = false;
            if (Request.IsAuthenticated)
            {
                pnlYourRating.Visible = true;
                Acms.Bll.UserPostUploadVote vote = Acms.Bll.UserPostUploadVote.GetByUserIdAndUploadId(User.Identity.User.Id, Selected.Id);
                if (vote != null)
                {
                    yourRating.CurrentRating = (int)Math.Round(vote.Score * yourRating.MaxRating, MidpointRounding.AwayFromZero);
                    hasRatedSelect = true;
                }
                else
                {
                    yourRating.CurrentRating = 0;
                }
            }
            else
            {
                pnlYourRating.Visible = false;
            }
            
            //ave rating
            aveRating.CurrentRating = (int)Math.Round(selected.Average * aveRating.MaxRating, MidpointRounding.AwayFromZero);

           //if entrant reported then show has been
            if (Selected.Suspended)
            {
                pnlSelected.Visible = false;
                pnlSuspended.Visible = true;

            }
            else if (Selected.Reported)
            {
                btnReport.Visible = false;
                lblReported.Visible = true;
            }
            else 
            {
                lblReported.Visible = false;
                btnReport.Visible = !Selected.Reviewed;
                if(Request.IsAuthenticated)
                {
                    if (Selected.UserId == User.Identity.User.Id)
                    {
                        btnReport.Visible = false;
                    }
                }
            }
        }

    }

    protected void btnViewEntry_Click(object sender, EventArgs e)
    {
        Selected = null;
        try
        {
            selectedId = int.Parse(((LinkButton)sender).CommandArgument as string);
        }
        catch (FormatException)
        {
        }
        pnlSelected.DataBind();
        updSelected.Update();
    }

    protected void dlEntrants_ItemCommand(object sender, Acms.WebControls.AcmsDataListItemCommandEventArgs e)
    {
        if (e.CommandName == "Show")
        {
            try
            {
                selectedId = int.Parse(e.CommandArgument as string);
            }
            catch (FormatException)
            {
            }
            pnlSelected.DataBind();
            updSelected.Update();
        }
    }
    protected void dlEntrants_ItemDataBound(object sender, Acms.WebControls.AcmsDataListItemEventArgs e)
    {
        if (e.Item.IsSeperator)
        {
            if (e.Item.ItemIndex > 0 && (e.Item.ItemIndex + 1) % 3 == 0)
                e.Item.Visible = true;
            else
                e.Item.Visible = false;
        }
        else if (e.Item.IsDataItem)
        {
            Image imgSuspended = e.Item.FindControl("imgSuspended") as Image;
            ImageButton imgReported = e.Item.FindControl("imgReported") as ImageButton;
            Acms.AcmsControls.AcmsImageLinkButton imgThumb = e.Item.FindControl("imgThumb") as Acms.AcmsControls.AcmsImageLinkButton;
            Acms.Bll.UserPostUpload image = e.Item.DataItem as Acms.Bll.UserPostUpload;
            if (image != null && imgSuspended != null && imgReported != null && imgThumb != null)
            {
                imgSuspended.Visible = false;
                imgReported.Visible = false;
                imgThumb.Visible = false;
                if(image.Suspended)
                {
                    imgSuspended.Visible = true;
                }
                else if (image.Reported)
                {
                    imgReported.Visible = true;
                }
                else
                {
                    imgThumb.Visible = true;
                }

            }
        }
    }

    protected void yourRating_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
    {
        Acms.Bll.UserPostUploadVote vote = null;
        if (hasRatedSelect)
        {
            vote = Acms.Bll.UserPostUploadVote.GetByUserIdAndUploadId(User.Identity.User.Id, Selected.Id);
        }
        else
        {
            vote = Acms.Bll.UserPostUploadVote.CreateInstance(User.Identity.User.Id, Selected.Id);
        }

        if (vote != null)
        {
            vote.Score = (decimal)yourRating.CurrentRating / (decimal)yourRating.MaxRating;
            vote.Update();
            selected = null;
            pnlSelected.DataBind();
            updSelected.Update();
        }
    }

    protected void btnReport_Click(object sender, EventArgs e)
    {
        if (selectedId > 0)
        {
            Acms.Bll.UserPostUpload upload = Acms.Bll.UserPostUpload.GetById(selectedId);
            if (upload != null)
            {
                upload.Reported = true;
                upload.Update();
            }
            pnlSelected.DataBind();
            dlEntrants.DataBind();
            updEntrants.Update();
        }
    }
}
